package org.array.struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.array.struts.action.ActionMapping;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class StrutsConfig {

	@SuppressWarnings("unchecked")
	public static Map<String, ActionMapping> getConfig(String filepath){
		
		Map<String, ActionMapping> map = new HashMap<String, ActionMapping>();
		try {
			Document doc = new SAXReader().read(new File(filepath));
			Element root = doc.getRootElement();
			Iterator<Element> elementIte = root.elementIterator();
			
			while (elementIte.hasNext()) {
				ActionMapping action = new ActionMapping();
				Element actions = elementIte.next();
				action.setPath(actions.attributeValue("path"));
				action.setType(actions.attributeValue("type"));
				action.setName(actions.attributeValue("name"));

				Iterator<Element> forwards = actions.elementIterator("forward");
				Map<String,String> forwardMap = new HashMap<String, String>();

				while(forwards.hasNext()){
				  Element els = forwards.next();
				  forwardMap.put(els.attributeValue("name"), els.getText());
				}
				
				action.setForward(forwardMap);
				map.put(actions.attributeValue("path"), action);				
			}
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return map;
	}
		
		
		
		
	

}
